﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Hosting;
using System.Web;
using System.Reflection;

namespace RssReader.Core.Global
{
	public class RssVirtualPathProvider : VirtualPathProvider
	{
		#region Private Properties

		#endregion

		#region Public Properties

		#endregion

		#region Constructors
		public RssVirtualPathProvider()
		{
		}
		#endregion

		#region Private Methods
		private bool IsVirtualPath(string virtualPath)
		{
			string checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
			return checkPath.StartsWith("~/AssemblyResources/", StringComparison.InvariantCultureIgnoreCase);
		}


		#endregion

		#region Public Methods
		public override bool FileExists(string virtualPath)
		{
			return IsVirtualPath(virtualPath) || base.FileExists(virtualPath);
		}

		public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
		{
			if (IsVirtualPath(virtualPath))
			{
				string path = HttpRuntime.BinDirectory;

				return new System.Web.Caching.CacheDependency(path);
			}
			else
				return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
		}

		public override VirtualFile GetFile(string virtualPath)
		{
			if (IsVirtualPath(virtualPath))
			{
				return new RssVirtualFile(virtualPath);
			}
			else
			{
				return base.GetFile(virtualPath);
			}
		}
		#endregion
	}

	class RssVirtualFile : VirtualFile
	{
		private string _path;

		public RssVirtualFile(string virtualPath)
			: base(virtualPath)
		{
			_path = VirtualPathUtility.ToAppRelative(virtualPath);
		}
		public override System.IO.Stream Open()
		{
			string[] parts = _path.Split('/');
			string assemName = parts[2];
			string resourceName = parts[3];
			return Assembly.Load(assemName).GetManifestResourceStream(resourceName);
		}
	}
}
